<?php declare(strict_types=1);
namespace App\Library\Core;

use App\Exception\ApiException;
use Swoft\Bean\BeanFactory;
use Swlib\SaberGM;
use Swoft\Log\Helper\Log;

class Api
{
    /**
     * @param string $service
     * @param string $path
     * @param array $params
     * @param string $method
     * @return array
     */
    public function call(string $service , string $path , array $params , string $method = "POST") : array
    {
        $consulLogic = BeanFactory::getBean('ConsulLogic');
        $serviceInfo = $consulLogic->getServiceList($service);
        if(!$serviceInfo)
        {
//            throw new ApiException(ErrCode::msg(ErrCode::SERVICE_NOTFOUND), ErrCode::SERVICE_NOTFOUND);
            return [
                'code'  => ErrCode::SERVICE_NOTFOUND,
                'msg'   => ErrCode::msg(ErrCode::RESPONSE_ERR),
                'error' => ErrCode::msg(ErrCode::SERVICE_NOTFOUND),
                'file'  => ''
            ];
        }

        $url = 'http://' . $serviceInfo ['Address'].':'.$serviceInfo['Port'] ;
        if ($path)
        {
            $path = str_replace('.' , '/' ,$path);
            $url .= '/'. $path;
        }

        switch ($method) {
            case 'GET':
                $res = SaberGM::get($url .'?'.http_build_query($params) , ['timeout'=>60])->getParsedJsonArray();
                break;
            case 'POST' :
                $res = SaberGM::post($url , $params ,['timeout'=>60])->getParsedJsonArray();
                break;
            default:
                $res = SaberGM::post($url , $params ,['timeout'=>60])->getParsedJsonArray();
                break;
        }

        if (!$res)
        {
            throw new ApiException(ErrCode::msg(ErrCode::RESPONSE_ERR) ,ErrCode::RESPONSE_ERR );
            Log::error('服务 %s 返回异常。path: %s ; params: %s ; response : %s' , $service , $path ,json_encode($params) , json_encode($res));
        }
        return $res;
    }

}